package com.xb.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xb.entity.*;
import com.xb.mapper.*;
import com.xb.service.IMedicalRecordService;
import com.xb.util.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * entityService业务层处理
 */
@Service
public class MedicalRecordServiceImp implements IMedicalRecordService {
    @Resource
    private MedicalRecordMapper medicalRecordMapper;
    @Resource
    private OutpatientQueueMapper outpatientQueueMapper;
    @Resource
    private DrugMapper drugMapper;
    @Resource
    private PatientMapper patientMapper;
    @Resource
    private RegisterMapper registerMapper;
    @Resource
    private TollTakeDrugMapper tollTakeDrugMapper;

    @Resource
    private UserMapper userMapper;

    /**
     * 分页查询entity列表
     *
     * @param medicalRecord entity
     * @return entity
     */
    @Override
    public PageInfo<MedicalRecord> selectMedicalRecordList(MedicalRecord medicalRecord, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<MedicalRecord> list = medicalRecordMapper.selectMedicalRecordList(medicalRecord);
        return new PageInfo<MedicalRecord>(list);
    }


    /**
     * 修改entity
     *
     * @param medicalRecord entity
     * @return 结果
     */
    @Transactional
    @Override
    public Result updateMedicalRecord(MedicalRecord medicalRecord, HttpSession session) {
        Result result = new Result();
        try {
            if (medicalRecordMapper.selectMedicalRecordByPrescriptionNum(medicalRecord.getPrescriptionNum()) == null) {
                result.setStatus(Result.RESPONSE_FAIL);
                result.setMessage("不存在该用户记录！");
            }
            String email = (String) session.getAttribute("email");
            User user = userMapper.selectUserByEmail(email);
            if (medicalRecordMapper.updateMedicalRecord(medicalRecord) == 0) {
                result.setStatus(Result.RESPONSE_FAIL);
                result.setMessage("不存在该用户记录！");
                throw new IllegalAccessException("medicalRecord更新失败！");
            }
            if (outpatientQueueMapper.selectOutpatientStatus(medicalRecord.getCardId()) != null) {
                result.setStatus(Result.RESPONSE_FAIL);
                result.setMessage("此用户有条待处理的门诊！");
                throw new IllegalAccessException("此用户有条待处理的门诊！");
            }
            OutpatientQueue outpatientQueue = new OutpatientQueue();
            outpatientQueue.setStatus(-1);
            outpatientQueue.setPatientId(medicalRecord.getCardId());
            outpatientQueue.setUserId(user.getId());
            if (outpatientQueueMapper.updateStatus(outpatientQueue) == 0) {
                result.setStatus(Result.RESPONSE_FAIL);
                result.setMessage("不存在该用户记录！");
                throw new IllegalAccessException("outpatientQueue更新失败！");
            }
            result.setStatus(Result.RESPONSE_SUCCESS);
            return result;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            result.setStatus(Result.RESPONSE_EXCEPTION);
            result.setMessage("出现异常请联系管理员！");
            return result;
        }
    }

    @Transactional
    @Override
    public Result addMedicalRecord(MedicalRecord medicalRecord, HttpSession session) {
        Result result = new Result();
        try {
            if (medicalRecordMapper.updateMedicalRecord(medicalRecord) == 0) {
                result.setMessage("操作失败");
                throw new IllegalAccessException("medicalRecord更新失败");
            }

            String[] dataArray = medicalRecord.getDrugIds().split(",");
            Map<Integer, Integer> map = new HashMap<>();
            for (String element : dataArray) {
                int key = Integer.parseInt(element);
                map.put(key, map.getOrDefault(key, 0) + 1);
            }

            // 暂不修改商品表
//            Drug drug;
//            for (int key : map.keySet()) {
//                drug = drugMapper.selectDrugById(key);
//                if (drug.getDrugCount() < map.get(key) || drug.getDrugCount() < 0) {
//                    result.setMessage(drug.getName() + "库存不足");
//                    throw new IllegalAccessException(drug.getName() + "库存不足");
//                }
//                drug.setDrugCount(drug.getDrugCount() - map.get(key));
//
//                if (drugMapper.updateDrug(drug) == 0) {
//                    result.setMessage("操作失败");
//                    throw new IllegalAccessException("drug更新失败");
//                }
//            }
            String email = (String) session.getAttribute("email");
            User user = userMapper.selectUserByEmail(email);
            OutpatientQueue outpatientQueue = new OutpatientQueue();
            outpatientQueue.setStatus(0);
            outpatientQueue.setPatientId(medicalRecord.getCardId());
            outpatientQueue.setUserId(user.getId());
            if (outpatientQueueMapper.updateStatus(outpatientQueue) == 0) {
                result.setMessage("操作失败");
                throw new IllegalAccessException("outpatientQueue更新失败");
            }
            if (medicalRecordMapper.selectMedicalRecordByRegisterId(medicalRecord.getRegisterId()) == null) {
                result.setMessage("不存在该用户记录！");
                throw new IllegalAccessException("不存在该用户记录！--medicalRecord");
            }

            Patient patient = new Patient();
            patient.setCardId(String.valueOf(medicalRecord.getCardId()));
            patient.setCareer(medicalRecord.getCareer());
            patient.setFamilyHistory(medicalRecord.getFamilyHistory());
            patient.setMaritalStatus(medicalRecord.getMaritalStatus());
            patient.setPastHistory(medicalRecord.getPastHistory());
            patient.setPersonalHistory(medicalRecord.getPersonalHistory());
            if (patientMapper.updatePatientByCardId(patient) == 0) {
                result.setMessage("操作失败！");
                throw new IllegalAccessException("patient更新失败");
            }

            Register register = new Register();
            register.setId(medicalRecord.getRegisterId());
            register.setTreatmentStatus(1);
            if (registerMapper.updateRegister(register) == 0) {
                result.setMessage("操作失败！");
                throw new IllegalAccessException("register更新失败");
            }

            TollTakeDrug tollTakeDrug = new TollTakeDrug();
            tollTakeDrug.setPrescriptionNum(medicalRecord.getPrescriptionNum());
            tollTakeDrug.setTakingDrugStatus(-1);
            if (tollTakeDrugMapper.updateTollTakeDrug(tollTakeDrug) == 0) {
                result.setMessage("操作失败！");
                throw new IllegalAccessException("tollTakeDrug更新失败");
            }
            result.setStatus(Result.RESPONSE_SUCCESS);
            return result;

        } catch (IllegalAccessException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return result;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            result.setStatus(Result.RESPONSE_EXCEPTION);
            result.setMessage("出现异常了！");
            return result;
        }


    }

}
